import 'dart:convert';
import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_animation/DouBao/SoundButton/sounds_button_copy.dart';
import 'package:flutter_animation/More/widget/photo_list.dart';
import 'package:flutter_animation/Utils/DB/MessageDao.dart';
import 'package:flutter_animation/Utils/FileUploadUtil.dart';
import 'package:flutter_animation/Utils/TTSUtil.dart';
import 'package:flutter_animation/DouBao/SoundButton/recorder_copy.dart';
import 'package:flutter_animation/Utils/XFUtil/XFUtil.dart';
import 'package:flutter_animation/Widgets/MarkDownWidget/code_wrapper.dart';
import 'package:flutter_animation/Widgets/MarkDownWidget/custom_node.dart';
import 'package:flutter_animation/Widgets/MarkDownWidget/latex.dart';
import 'package:flutter_animation/Widgets/MarkDownWidget/video.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:image_picker/image_picker.dart';
import 'package:markdown_widget/markdown_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

import '../Utils/ColorUtil.dart';
import '../Utils/SSEUtil/constants/sse_request_type_enum.dart';
import '../Utils/SSEUtil/flutter_client_sse.dart';
import 'MessageModel.dart';

class DouBao extends StatefulWidget {
  const DouBao({super.key});

  @override
  State<DouBao> createState() => _DouBaoState();
}

class _DouBaoState extends State<DouBao> with TickerProviderStateMixin{
  // 输入控件key
  GlobalKey editAreaKey = GlobalKey();
  GlobalKey statusKey = GlobalKey();
  RenderBox? editAreaRenderBox;
  // 文本输入控制器
  TextEditingController editTextController = TextEditingController();
  // 是否正在回答
  bool isAnswering = false;
  // 是否展示语音输入
  bool showVoiceButton = false;
  final ScrollController _scrollController = ScrollController();
  // 是否展示滚动按钮
  bool showScrollButton = false;
  // 是否展示菜单
  bool showMenu = false;
  // 菜单当前视图
  CrossFadeState _crossFadeState = CrossFadeState.showFirst;
  // 菜单动画控制器
  late final AnimationController _menuAnimationController = AnimationController(
    duration: const Duration(milliseconds: 200),
    reverseDuration: const Duration(milliseconds: 200),
    vsync: this,
  );
  
  // 是否静音
  bool isMute = false;
  // 锚点动画控制器
  late final AnimationController _anchorAnimationController = AnimationController(
    duration: const Duration(milliseconds: 500),
    reverseDuration: const Duration(milliseconds: 500),
    vsync: this,
  );

  late SharedPreferences prefs;

  // 消息列表
  List<MessageModel> messages = [];

  // 已选图片列表
  List<FileModel> selectedImages = [];
  // 照片选择器
  final ImagePicker _imagePicker = ImagePicker();

  @override
  void initState() {
    super.initState();

    WidgetsBinding.instance.addPostFrameCallback((callback){
      editAreaRenderBox = editAreaKey.currentContext!.findRenderObject() as RenderBox?;
    });

    _scrollController.addListener(() {
      if (showScrollButton == false && _scrollController.position.pixels >= 500) {
        setState(() {
          showScrollButton = true;
          _anchorAnimationController.reverse();
        });
      } else if (showScrollButton == true && _scrollController.position.pixels < 500) {
        setState(() {
          showScrollButton = false;
          _anchorAnimationController.forward();
        });
      }
    });

    // 获取本地信息
    getLocalMessage();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Column(
        children: [
          SizedBox(height: MediaQuery.of(context).padding.top),
          buildBar(),
          Expanded(child: buildMainView()),
          buildImage(),
          buildCommand(),
          buildTextArea(),
          buildMenu(),
        ],
      ),
    );
  }

  /// 顶部信息
  buildBar() {
    return Container(
      color: Colors.white,
      padding: const EdgeInsets.all(10),
      child: Row(
        children: [
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              SmartDialog.showToast('点击返回',displayType: SmartToastType.last);
            },
            child: Image.asset(
              'assets/images/arrow_backward_outlined.webp',
              width: 24,
              height: 24,
            ),
          ),
          Expanded(
            child: GestureDetector(
              behavior: HitTestBehavior.opaque,
              onTap: () {
                SmartDialog.showToast('点击信息',displayType: SmartToastType.last);
              },
              child: const Row(
                children: [
                  SizedBox(width: 16),
                  CircleAvatar(
                    radius: 18,
                    backgroundColor: Colors.transparent,
                    backgroundImage: AssetImage(
                      'assets/images/doubao_avatar.png',
                    ),
                  ),
                  SizedBox(width: 5),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '豆包',
                          style: TextStyle(
                            fontSize: 14,
                            color: Colors.black,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                        Text(
                          'doubao.com',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey,
                            overflow: TextOverflow.ellipsis,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
            },
            child: Image.asset(
              'assets/images/ic_s_s_phoneup_outlined.webp',
              width: 28,
              height: 28,
              color: Colors.black,
            ),
          ),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              setState(() {
                isMute = !isMute;
              });
            },
            child: Image.asset(
              isMute ? 'assets/images/ic_tts_disable.png' : 'assets/images/ic_tts_enable.png',
              width: 50,
              height: 50,
              color: isMute ? Colors.black : ColorUtil.primary,
            ),
          ),
          const SizedBox(width: 10),
          GestureDetector(
            behavior: HitTestBehavior.opaque,
            onTap: () {
              SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
            },
            child: Image.asset(
              'assets/images/ic_screen_menu_more.png',
              width: 28,
              height: 28,
              color: Colors.black,
            ),
          ),
        ],
      ),
    );
  }

  /// 聊天视图
  buildMainView() {
    return GestureDetector(
      onPanDown: (details) {
        menuStatusChange(false);
      },
      child: Stack(
        children: [
          ListView(
            controller: _scrollController,
            reverse: true,
            shrinkWrap: true,
            physics: const BouncingScrollPhysics(),
            children: messages.map<Widget>((MessageModel item) =>
              Column(
                crossAxisAlignment: item.userType == 1 ? CrossAxisAlignment.end : CrossAxisAlignment.start,
                children: [
                  GestureDetector(
                    onLongPressStart: (detail) { 
                      SmartDialog.showAttach(
                        targetContext: null,
                        targetBuilder: (Offset targetOffset, Size targetSize) {
                          Offset offset = const Offset(100, 0);
                          return detail.globalPosition + offset;
                        },
                        usePenetrate: true,
                        useAnimation: false,
                        builder: (_) {
                          return GestureDetector(
                            onTap: () {
                              SmartDialog.dismiss();
                              SmartDialog.showToast('点击dialog',displayType: SmartToastType.last);
                            },
                            child: Container(
                              margin: const EdgeInsets.all(10),
                              width: 200,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(15),
                                color: ColorUtil.colorWhite,
                                boxShadow: [
                                  BoxShadow(color: Colors.black.withOpacity(0.2), blurRadius: 5, offset: Offset(0.0,2))
                                ],
                              ),
                              child: ClipRRect(
                                borderRadius: BorderRadius.circular(15),
                                child: Column(
                                  children: [
                                    buildCommandItem(
                                      'assets/images/command.png',
                                      text: '复制',
                                      () {
                                        SmartDialog.dismiss();
                                        SmartDialog.showToast('点击复制',displayType: SmartToastType.last);
                                      },
                                      radius: 0,
                                      borderColor: ColorUtil.transparent,
                                      height: 50,
                                      fontSize: 18,
                                    ),
                                    Container(
                                      height: 1,
                                      color: ColorUtil.color999999_30,
                                    ),
                                    buildCommandItem(
                                      'assets/images/command.png',
                                      text: '复制',
                                      () {
                                        SmartDialog.dismiss();
                                        SmartDialog.showToast('点击复制',displayType: SmartToastType.last);
                                      },
                                      radius: 0,
                                      borderColor: ColorUtil.transparent,
                                      height: 50,
                                      fontSize: 18,
                                    ),
                                    Container(
                                      height: 1,
                                      color: ColorUtil.color999999_30,
                                    ),
                                    buildCommandItem(
                                      'assets/images/command.png',
                                      text: '复制',
                                      () {
                                        SmartDialog.dismiss();
                                        SmartDialog.showToast('点击复制',displayType: SmartToastType.last);
                                      },
                                      radius: 0,
                                      borderColor: ColorUtil.transparent,
                                      height: 50,
                                      fontSize: 18,
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          );
                        },
                      );
                    },
                    onPanDown: (detail) {
                      SmartDialog.dismiss();
                    },
                    child: Container(
                      padding: item.imageUrlList.isEmpty ? const EdgeInsets.all(10) : const EdgeInsets.all(0),
                      margin: const EdgeInsets.symmetric(horizontal: 10,vertical: 5),
                      decoration: BoxDecoration(
                        color: item.userType == 1 ?
                        (item.imageUrlList.isEmpty ?
                        ColorUtil.primary :
                        ColorUtil.transparent) :
                        ColorUtil.color999999_10,
                        borderRadius: BorderRadius.circular(15),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          item.userType == 1 ?
                          (item.imageUrlList.isEmpty ?
                          buildUserText(item.messageContent) :
                          buildUserImage(item.imageUrlList)) :
                          buildDouBaoText(item.messageContent, messages.indexOf(item) == 0 && item.userType == 0 && !isAnswering),
                          messages.indexOf(item) == 0 && item.userType == 0 && !isAnswering ?
                          buildMessageCommand(item) : SizedBox.shrink(),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ).toList(),
          ),
          SlideTransition(
            position: Tween<Offset>(
              begin: const Offset(0, 0),
              end: const Offset(0, 0.13),
            ).animate(_anchorAnimationController),
            child: Padding(
              padding: const EdgeInsets.only(bottom: 10),
              child: AnimatedOpacity(
                duration: const Duration(milliseconds: 500),
                opacity: showScrollButton ? 1.0 : 0.0,
                curve: Curves.ease,
                child: Align(
                  alignment: Alignment.bottomCenter,
                  child: FloatingActionButton(
                    mini: true,
                    backgroundColor: ColorUtil.colorWhite,
                    shape: const CircleBorder(),
                    onPressed: () {
                      scroll(bottom: true);
                    },
                    child: Padding(
                      padding: const EdgeInsets.all(10),
                      child: Image.asset(
                        'assets/images/scroll_arrow.png',
                        color: ColorUtil.colorBlack,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 用户图片消息
  buildUserImage(List<String> imageUrlList) {
    return SizedBox(
      height: 100,
      child: SingleChildScrollView(
        physics: const BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        child: Row(
          children: imageUrlList.map<Widget>((String url) {
            int index = imageUrlList.indexOf(url);
            return Row(
              children: [
                Card(
                  margin: EdgeInsets.all(0),
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadiusDirectional.circular(5),
                  ),
                  clipBehavior: Clip.antiAlias,
                  child: Image.network(
                    url,
                    gaplessPlayback: true,
                    fit: BoxFit.cover,
                    width: 100,
                    height: 100,
                  ),
                ),
                index == imageUrlList.length - 1 ? SizedBox.shrink() : SizedBox(width: 10),
              ],
            );
          }).toList(),
        ),
      ),
    );
  }

  /// 用户文本消息
  buildUserText(String text) {
    return Text(
      text,
      style: const TextStyle(
        color: Colors.white,
        fontSize: 16,
      ),
      textAlign: TextAlign.end,
    );
  }

  /// 豆包大模型文本消息
  buildDouBaoText(String text, bool showCommand) {
    return Container(
      padding: EdgeInsets.only(bottom: showCommand ? 10 : 0),
      margin: EdgeInsets.only(bottom: showCommand ? 10 : 0),
      decoration: showCommand ? BoxDecoration(
        border: Border(
          bottom: BorderSide(color: ColorUtil.color999999_50, width: 0.5),
        ),
      ) : null,
      child: SingleChildScrollView(
        child: MarkdownBlock(
          selectable: false,
          data: text,
          config: MarkdownConfig(
            configs: [
              const PreConfig().copy(wrapper: (child, text, language) => CodeWrapperWidget(child, text, language)),
              LinkConfig(
                style: const TextStyle(
                  color: ColorUtil.primary,
                  decoration: TextDecoration.underline,
                ),
                onTap: (url) {
                  Uri? uri = Uri.tryParse(url);
                  if (uri != null) {
                    launchUrl(uri);
                  }
                },
              ),
            ],
          ),
          generator: MarkdownGenerator(
            generators: [videoGeneratorWithTag, latexGenerator],
            inlineSyntaxList: [LatexSyntax()],
            textGenerator: (node, config, visitor) =>
              CustomTextNode(
                node.textContent,
                config,
                visitor,
              ),
            richTextBuilder: (span) =>
              Text.rich(span),
            linesMargin: const EdgeInsets.all(0),
          ),
        ),
      ),
    );
  }

  /// 消息操作视图
  buildMessageCommand(MessageModel item) {
    return SingleChildScrollView(
      physics: const BouncingScrollPhysics(),
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
          buildCommandItem(
            'assets/images/ic_screen_menu_copy.png',
            () {
              SmartDialog.showToast('点击复制',displayType: SmartToastType.last);
            },
            contentColor: ColorUtil.primary,
            backgroundColor: ColorUtil.primary_10,
            borderColor: ColorUtil.transparent,
          ),
          const SizedBox(width: 10),
          buildCommandItem(
            'assets/images/ic_screen_menu_dislike_normal.png',
            () {
              SmartDialog.showToast('点击更差',displayType: SmartToastType.last);
            },
            contentColor: ColorUtil.primary,
            backgroundColor: ColorUtil.primary_10,
            borderColor: ColorUtil.transparent,
          ),
          const SizedBox(width: 10),
          buildCommandItem(
            'assets/images/ic_msg_tts_action.png',
            () {
              TTSUtil().speak(item.messageContent);
            },
            contentColor: ColorUtil.primary,
            backgroundColor: ColorUtil.primary_10,
            borderColor: ColorUtil.transparent,
          ),
          const SizedBox(width: 10),
          buildCommandItem(
            'assets/images/ic_share_arrow.png',
            () {
              SmartDialog.showToast('点击转发',displayType: SmartToastType.last);
            },
            contentColor: ColorUtil.primary,
            backgroundColor: ColorUtil.primary_10,
            borderColor: ColorUtil.transparent,
          ),
          const SizedBox(width: 10),
          buildCommandItem(
            'assets/images/ic_screen_menu_regenerate.png',
            () {
              SmartDialog.showToast('点击重新加载',displayType: SmartToastType.last);
            },
            contentColor: ColorUtil.primary,
            backgroundColor: ColorUtil.primary_10,
            borderColor: ColorUtil.transparent,
          ),
        ],
      ),
    );
  }

  /// 已选图片视图
  buildImage() {
    if (selectedImages.isEmpty) {
      return SizedBox.shrink();
    } else {
      return Container(
        color: Colors.white,
        padding: EdgeInsets.symmetric(vertical: 10),
        child: SizedBox(
          width: double.infinity,
          height: 60,
          child: SingleChildScrollView(
            physics: const BouncingScrollPhysics(),
            scrollDirection: Axis.horizontal,
            child: Row(
              children: selectedImages.map<Widget>((FileModel fileModel) {
                int index = selectedImages.indexOf(fileModel);
                return Container(
                  padding: const EdgeInsets.only(left: 10),
                  child: Stack(
                    children: [
                      Card(
                        margin: EdgeInsets.all(0),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadiusDirectional.circular(5),
                        ),
                        clipBehavior: Clip.antiAlias,
                        child: Image.file(
                          fileModel.file,
                          fit: BoxFit.cover,
                          width: 60,
                          height: 60,
                        ),
                      ),
                      fileModel.progress == fileModel.total ? SizedBox.shrink() :
                      Positioned(
                        top: 0,
                        right: 0,
                        bottom: 0,
                        left: 0,
                        child: Container(
                          color: ColorUtil.colorBlack_30,
                          padding: EdgeInsets.all(20),
                          child: CircularProgressIndicator(
                            value: fileModel.progress/fileModel.total,
                            color: ColorUtil.colorWhite,
                            strokeWidth: 3,
                          ),
                        ),
                      ),
                      Positioned(
                        top: 0,
                        right: 0,
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              selectedImages.removeAt(index);
                            });
                          },
                          child: Container(
                            padding: EdgeInsets.all(2),
                            decoration: BoxDecoration(
                              borderRadius: BorderRadius.only(
                                topRight: Radius.circular(5),
                                bottomLeft: Radius.circular(5),
                              ),
                              color: ColorUtil.colorBlack_30,
                            ),
                            child: Icon(
                              Icons.close,
                              color: ColorUtil.colorWhite,
                              size: 12,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ),
        ),
      );
    }
  }

  /// 命令视图
  buildCommand() {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          Expanded(
            child: SingleChildScrollView(
              physics: const BouncingScrollPhysics(),
              scrollDirection: Axis.horizontal,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 10),
                child: Row(
                  children: [
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '前往顶部',
                      () {
                        scroll();
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                    const SizedBox(width: 10),
                    buildCommandItem(
                      'assets/images/command.png',
                      text: '更多',
                      () {
                        SmartDialog.showToast('点击更多',displayType: SmartToastType.last);
                      },
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 消息列表滚动
  scroll({bool bottom = false}) {
    if (_scrollController.position.pixels != (bottom ? _scrollController.position.minScrollExtent : _scrollController.position.maxScrollExtent)) {
      _scrollController.animateTo(bottom ? _scrollController.position.minScrollExtent : _scrollController.position.maxScrollExtent, duration: const Duration(milliseconds: 200), curve: Curves.linear);
    }
  }

  buildCommandItem(
    String imgPath,
    void Function() onPressed,
    {
      double height = 40,
      String text = '',
      double fontSize = 14,
      double radius = 15,
      Color contentColor = ColorUtil.colorBlack,
      Color backgroundColor = ColorUtil.transparent,
      Color borderColor = ColorUtil.color999999_10,
      Color overlayColor = ColorUtil.color999999_10,
    }
  ) {
    return SizedBox(
      height: height,
      width: text.isEmpty ? height : null,
      child: TextButton(
        style: ButtonStyle(
          backgroundColor: WidgetStatePropertyAll(backgroundColor),
          shape: WidgetStatePropertyAll(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(radius)),
            ),
          ),
          side: WidgetStatePropertyAll(
            BorderSide(
              width: 1,
              color: borderColor,
            ),
          ),
          overlayColor: WidgetStatePropertyAll(overlayColor),
        ),
        onPressed: onPressed,
        child: text.isEmpty ?
        Image.asset(
          imgPath,
          color: contentColor,
        ) :
        Row(
          children: [
            Image.asset(
              imgPath,
              color: contentColor,
            ),
            Text(
              text,
              style: TextStyle(
                fontSize: fontSize,
                color: contentColor,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 输入视图
  buildTextArea() {
    return Column(
      children: [
        // showVoiceButton ? RecordingBotSpace(
        //   statusKey: statusKey,
        //   scrollController: _scrollController,
        // ) : SizedBox.shrink(),
        Container(
          key: editAreaKey,
          margin: const EdgeInsets.symmetric(horizontal: 16),
          padding: EdgeInsets.symmetric(horizontal: 10),
          width: double.infinity,
          alignment: Alignment.center,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(15),
            color: Colors.white,
            boxShadow: [
              BoxShadow(color: Colors.black.withOpacity(0.2), blurRadius: 5, offset: Offset(0.0,2))
            ],
          ),
          child: Row(
            children: [
              Expanded(
                child: Container(
                  padding: const EdgeInsets.symmetric(vertical: 10),
                  alignment: Alignment.center,
                  child: showVoiceButton ?
                  /// 仿微信语音
                  // SoundsMessageButton(
                  //   key: statusKey,
                  //   onSendSounds: (type,value) {
                  //     if (type == SendContentType.text) {
                  //       editTextController.text = value;
                  //       sendMessage();
                  //     }
                  //     if (type == SendContentType.voice) {
                  //       STT(value);
                  //       // sendMessage();
                  //     }
                  //   },
                  // ) :
                  /// 仿豆包语音
                  SoundsMessageButtonCopy(
                    editAreaRenderBox: editAreaRenderBox,
                    onSendSounds: (type,value) {
                      if (type == SendContentType.voice) {
                        STT(value);
                      }
                    },
                  ) :
                  TextField(
                    controller: editTextController,
                    decoration: const InputDecoration(
                      isCollapsed: true,
                      border: InputBorder.none,
                      hintText: '发消息...',
                      hintStyle: TextStyle(
                        fontSize: 18,
                        color: ColorUtil.color999999,
                        fontWeight: FontWeight.normal,
                      ),
                      counterText: '',
                    ),
                    style: TextStyle(
                      fontSize: 18
                    ),
                    textAlign: TextAlign.start,
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    minLines: 1,
                    onChanged: (value) {
                      setState(() {});
                    },
                  ),
                ),
              ),
              editTextController.text.isEmpty || editTextController.text.trim().isEmpty ? 
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  setState(() {
                    showVoiceButton = !showVoiceButton;
                  });
                },
                child: Container(
                  padding: const EdgeInsets.fromLTRB(10, 5, 0, 5),
                  child: Image.asset(
                    showVoiceButton ? 'assets/images/ic_keyboard_normal.png' : 'assets/images/ic_mic_normal.png',
                    color: Colors.black,
                    width: 30,
                    height: 30,
                  ),
                ),
              ) : const SizedBox.shrink(),
              selectedImages.isEmpty && (editTextController.text.isEmpty || editTextController.text.trim().isEmpty) ? 
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
                  if (showMenu) {
                    menuStatusChange(false);
                  } else {
                    menuStatusChange(true);
                  }
                },
                child: Container(
                  padding: const EdgeInsets.fromLTRB(10, 5, 0, 5),
                  child: RotationTransition(
                    turns: Tween(begin: 0.0, end: 0.125).animate(_menuAnimationController),
                    child: Image.asset(
                      'assets/images/icon_chat_bottom_menu_entrance.png',
                      color: Colors.black,
                      width: 30,
                      height: 30,
                    ),
                  ),
                ),
              ) : const SizedBox.shrink(),
              selectedImages.isEmpty && (editTextController.text.isEmpty || editTextController.text.trim().isEmpty) ? const SizedBox.shrink() :
              IgnorePointer(
                ignoring: selectedImages.where((element) => element.url.isNotEmpty).toList().length != selectedImages.length,
                child: GestureDetector(
                  behavior: HitTestBehavior.opaque,
                  onTap: () async {
                    sendMessage();
                  },
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(10, 5, 0, 5),
                    child: Image.asset(
                      'assets/images/icon_arrow_up_circle_fill.png',
                      color: selectedImages.where((element) => element.url.isNotEmpty).toList().length != selectedImages.length ?
                      ColorUtil.primary_30 : ColorUtil.primary,
                      width: 30,
                      height: 30,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  /// 菜单视图
  buildMenu() {
    return AnimatedCrossFade(
      firstCurve: Curves.linear,
      secondCurve: Curves.linear,
      firstChild: Container(padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10)),
      secondChild: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16,vertical: 10),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            buildMenuItem(
              'assets/images/icon_chat_bottom_menu_camera.png',
              '相机',
              () {
                selectCamera();
              },
            ),
            buildMenuItem(
              'assets/images/icon_chat_bottom_menu_album.png',
              '相册',
              () {
                selectImage();
              },
            ),
            buildMenuItem(
              'assets/images/icon_chat_bottom_menu_file.png',
              '文件',
              () {
                
              },
            ),
            buildMenuItem(
              'assets/images/ic_s_s_phoneup_filled.webp',
              '打电话',
              () {
                
              },
            ),
          ],
        ),
      ),
      duration: Duration(milliseconds: 200),
      crossFadeState: _crossFadeState,
    );
  }

  /// 菜单项视图
  buildMenuItem(String assets, String label, GestureTapCallback onTap) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: onTap,
      child: Column(
        children: [
          TextButton(
            style: ButtonStyle(
              padding: WidgetStatePropertyAll(
                EdgeInsets.all(editAreaRenderBox == null? 25 : ((editAreaRenderBox!.size.width - 32)/4 - 40 - 8)/2)
              ),
              shape: const WidgetStatePropertyAll(
                RoundedRectangleBorder(
                  borderRadius: BorderRadius.all(Radius.circular(15)),
                ),
              ),
              backgroundColor: const WidgetStatePropertyAll(
                ColorUtil.color999999_10,
              ),
              overlayColor: const WidgetStatePropertyAll(ColorUtil.color999999_10),
            ),
            onPressed: onTap,
            child: Image.asset(
              assets,
              width: 40,
              height: 40,
            ),
          ),
          SizedBox(height: 10),
          Text(
            label,
            style: TextStyle(
              color: ColorUtil.colorBlack,
            ),
          ),
        ],
      ),
    );
  }

  /// 菜单状态切换
  menuStatusChange(bool menuStatus) {
    setState(() {
      showMenu = menuStatus;
      if (showMenu) {
        _menuAnimationController.forward();
        _crossFadeState = CrossFadeState.showSecond;
        scroll(bottom: true);
      } else {
        _menuAnimationController.reverse();
        _crossFadeState = CrossFadeState.showFirst;
      }
    });
  }

  /// 选择相册图片
  selectImage() async {
    if (Platform.isAndroid) {
      AndroidDeviceInfo androidInfo = await DeviceInfoPlugin().androidInfo;
      if (androidInfo.version.sdkInt < 33) {
        ImageUtils.pickImage(context, (value) async {
          if (value != null) {
            for (File element in value) {
              uploadImage(File(element.path));
            }
          }
        });
      } else {
        await _imagePicker.pickMultiImage().then((value) async {
          if (value.isNotEmpty) {
            for (XFile element in value) {
              uploadImage(File(element.path));
            }
          }
        });
      }
    } else {
      ImageUtils.pickImage(context, (value) async {
        if (value != null) {
          for (File element in value) {
            uploadImage(File(element.path));
          }
        }
      });
    }
  }

  /// 拍照
  selectCamera() async {
    await _imagePicker.pickImage(
      source: ImageSource.camera,
    ).then((value) async {
      if (value != null) {
        uploadImage(File(value.path));
      }
    });
  }

  uploadImage(File file) {
    int index = selectedImages.length;
    selectedImages.add(FileModel(file: file));
    setState(() {
      menuStatusChange(false);
    });

    FileUploadUtil.uploadImage(
      file,
      (int progress, int total) {
        setState(() {
          selectedImages[index].progress = progress;
          selectedImages[index].total = total;
        });
        print("第$index个照片的上传进度 ${progress/total*100}%");
      },
    ).then((url) {
      if (url != null) {
        print("第$index个照片的url $url");
        setState(() {
          selectedImages[index].url = url;
        });
      }
    });
  }

  /// 语音转文字
  STT(String path) async {
    Uint8List fileBytes = await File(path).readAsBytes();

    XFUtil.connect(
      // await MicRecord.currentSamples(),
      fileBytes,
      (msg) {
        if (msg.isEmpty || msg.trim().isEmpty) {
          SmartDialog.showToast('未识别到文字',displayType: SmartToastType.last);
        } else {
          editTextController.text = msg;
          sendMessage();
        }
      },
    );

  }

  sendMessage() async {
    // 消息文本
    String text = '';
    // 图片
    List<String> urlList = [];

    List<FileModel> uploadedImages = selectedImages.where((element) => element.url.isNotEmpty).toList();
    // 存储本地消息
    if (uploadedImages.isNotEmpty) {
      MessageModel userImages = MessageModel();

      userImages.id = DateTime.now().millisecondsSinceEpoch;

      urlList = uploadedImages.map((element) => element.url).toList();
      userImages.imageUrlList = urlList;
      selectedImages.clear();

      userImages.userType = 1;
      
      setState(() {
        messages.insert(0,userImages);
      });
      await setLocalMessage(userImages);
    }

    if (editTextController.text.isNotEmpty && editTextController.text.trim().isNotEmpty) {
      MessageModel userMessage = MessageModel();

      userMessage.id = DateTime.now().millisecondsSinceEpoch;

      text = editTextController.text;
      userMessage.messageContent = text;
      editTextController.clear();

      userMessage.userType = 1;
      setState(() {
        messages.insert(0,userMessage);
      });
      await setLocalMessage(userMessage);
    }
    

    /// 请求大模型接口
    Map<String,dynamic> params = {};
    List<Map<String,dynamic>> requestMessages = [];

    List content = [];

    // 图片信息
    if (urlList.isNotEmpty) {
      params['model'] = 'ep-20241220135958-2rlv4';
      for (String url in urlList) {
        content.add({
          'type': 'image_url',
          'image_url': {
            'url': url
          },
        });
      }
    } else {
      params['model'] = 'ep-20241112143244-l4g8n';
    }

    // 文本信息
    content.add({
      'type': 'text',
      'text': text,
    });

    requestMessages.add({
      'role': 'system',
      'content': '如果user没给你图片信息，你就直接回复文本信息；如果user给你了图片，你要描述图片；如果给你了多张图片，同时描述多张图片',
    });
    requestMessages.add({
      'role': 'user',
      'content': content,
    });
    params['messages'] = requestMessages;
    // true 流式, false 非流式 默认false
    params['stream'] = true;

    /// 非流式调用
    // Dio dio = Dio();
    // dio.options.headers["Authorization"]='Bearer 5c847c21-466f-4f81-b07d-984d8c308e42';
    // dio.options.contentType='application/json';
    // dio.post('https://ark.cn-beijing.volces.com/api/v3/chat/completions', data: params).then((response) {
    //   if (response.statusCode == 200 && response.data != null) {
    //     MessageModel sysMessage = MessageModel();
    //     sysMessage.id = DateTime.now().millisecondsSinceEpoch;
    //     sysMessage.messageContent = response.data['choices'][0]['message']['content'];
    //     sysMessage.isUser = 0;
    //     setState(() {
    //       messages.insert(0,sysMessage);
    //     });
    //     setLocalMessage(sysMessage);
    //   } else {
    //     SmartDialog.showToast('获取信息异常',displayType: SmartToastType.last);
    //   }
    // });

    /// 流式调用
    MessageModel sysMessage = MessageModel(messageContent: '...');
    setState(() {
      messages.insert(0,sysMessage);
      isAnswering = true;
    });
    print('请求参数：$params');
    SSEClient.subscribeToSSE(
      method: SSERequestType.POST,
      url:'https://ark.cn-beijing.volces.com/api/v3/chat/completions',
      header: {
        "Authorization":'Bearer 5c847c21-466f-4f81-b07d-984d8c308e42',
      },
      body: params,
    ).listen((event) {
      if (event.data != null) {
        dynamic data;
        try {
          data = jsonDecode(event.data!);
        } catch (e) {
          return;
        }

        if (data!['choices'][0]['finish_reason'] == 'stop') {
          // messages[0].messageContent += "[百度一下](https://www.baidu.com)";
          // messages[0].messageContent += '<video src="https://cdn.coverr.co/videos/coverr-walking-to-the-mountain-top-8360/1080p.mp4">';

          messages[0].id = DateTime.now().millisecondsSinceEpoch;
          setLocalMessage(messages[0]);
          setState(() {
            isAnswering = false;
          });
          return;
        }

        setState(() {
          if (messages[0].messageContent == '...') {
            messages[0].messageContent = '';
          }
          messages[0].messageContent += data!['choices'][0]['delta']['content'];
        });
      } else {
        messages[0].id = DateTime.now().millisecondsSinceEpoch;
        if (messages[0].messageContent == '...') {
          messages[0].messageContent = '获取信息异常';
        } else {
          SmartDialog.showToast('获取信息异常',displayType: SmartToastType.last);
        }
        setLocalMessage(messages[0]);
        setState(() {
          isAnswering = false;
        });
      }
    },
    onError: (error) {
      messages[0].id = DateTime.now().millisecondsSinceEpoch;
      if (messages[0].messageContent == '...') {
        messages[0].messageContent = '获取信息异常';
      } else {
        SmartDialog.showToast('获取信息异常',displayType: SmartToastType.last);
      }
      setLocalMessage(messages[0]);
      setState(() {
        isAnswering = false;
      });
    });
  }

  /// 存储数据库
  getLocalMessage() async {
    List<MessageModel> localMessages = await MessageDao.queryAll();
    print(localMessages);
    setState(() {
      messages = localMessages.reversed.toList();
    });
  }

  setLocalMessage(MessageModel messageModel) async {
    // bool isExist = await MessageDao.isExist(messageModel.id);
    // if(!isExist){
    //   int flag = await MessageDao.insert(messageModel);
    //   if (flag <= 0) {
    //     SmartDialog.showToast('写入失败',displayType: SmartToastType.last);
    //   }
    // }else{
    //   SmartDialog.showToast('主键重复',displayType: SmartToastType.last);
    // }
    int flag = await MessageDao.insert(messageModel);
    if (flag <= 0) {
      SmartDialog.showToast('写入失败',displayType: SmartToastType.last);
    }
  }
}
